package com.zhangyj.db.util;

class MSSQLUtil extends BaseDBUtil {

	
public	String buildPagnationSql(String sql, int pageNo, int size, int tatalCount, String orderField, String orderTable, boolean isDesc) {
		String desc = " desc";
		String asc = " asc";
		if (isDesc) {
			desc = " asc";
			asc = " desc";
		}
		String alias = "";
		if (orderTable != null && orderTable.trim().length() > 0) {
			alias = orderTable + ".";
		}
		StringBuffer buffer = new StringBuffer();
		if (pageNo == 1) {
			return buffer.append(sql.replaceFirst("select", "select top " + size)).append(" order by ").append(alias).append(orderField)
					.append(asc).toString();
		}
		StringBuffer tempSql = new StringBuffer();
		tempSql.append(sql.replaceFirst("select", "select top " + pageNo * size)).append(" order by ").append(alias).append(orderField)
				.append(asc);
		if (pageNo * size > tatalCount) {
			int tempSize = tatalCount - (pageNo - 1) * size;
			if (tempSize < 0) {
				return "";
			}
			buffer.append("select *").append(" from (select top ").append(tempSize).append(" * from (");
			buffer.append(tempSql);
			buffer.append(") a order by a.").append(orderField).append(desc).append(") b order by b.").append(orderField).append(asc);
			return buffer.toString();
		}
		buffer.append("select *").append(" from (select top ").append(size).append(" * from (");
		buffer.append(tempSql);
		buffer.append(") a order by a.").append(orderField).append(desc).append(") b order by b.").append(orderField).append(asc);
		return buffer.toString();
	}
}
